package com.kudian.restful.service;

import com.kudian.common.persistence.HibernateDao;
import com.kudian.common.service.BaseService;
import com.kudian.restful.dao.*;
import com.kudian.restful.entity.*;
import com.kudian.restful.vo.address.AddressItemVO;
import com.kudian.restful.vo.cart.AddCartInfoVO;
import com.kudian.restful.vo.cart.CartInfoItemVO;
import com.kudian.restful.vo.cart.QueryCartInfoVO;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/18.
 */
@Service
@Transactional(readOnly = true)
public class UserAddressService extends BaseService<UserAddress, Integer> {
    private static final Logger logger = Logger.getLogger(UserAddressService.class);

    @Autowired
    private UserAddressDao userAddressDao;

    @Autowired
    private RegionDao regionDao;

    @Override
    public HibernateDao<UserAddress, Integer> getEntityDao() {
        return userAddressDao;
    }

    public List<AddressItemVO> getAddresses(Integer userId) {
        List<AddressItemVO> ret = new ArrayList<AddressItemVO>();
        if (userId == null) {
            return ret;
        }

        List<UserAddress> uas = userAddressDao.findbyorder("addressId", false, Restrictions.eq("userId", userId));
        for (UserAddress ua : uas) {
            AddressItemVO vo = new AddressItemVO();
            vo.setConsignee(ua.getConsignee());
            vo.setSex(ua.getSex());
            vo.setProvince(ua.getProvince());
            vo.setCity(ua.getCity());
            vo.setDistrict(ua.getDistrict());
            vo.setProvinceNm(this.getRegion(ua.getProvince()));
            vo.setCityNm(this.getRegion(ua.getCity()));
            vo.setDistrictNm(this.getRegion(ua.getDistrict()));

            vo.setAddress(ua.getAddress());
            vo.setZipcode(ua.getZipcode());
            vo.setMobile(ua.getMobile());
            vo.setBestTime(ua.getBestTime());
            ret.add(vo);
        }

        return ret;
    }

    private String getRegion(Integer id) {
        Region r = this.regionDao.get(id);
        if (r == null) {
            return id.toString();
        }
        return r.getName();
    }
}
